package com.suhui.task.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suhui.task.common.Result;
import com.suhui.task.pojo.progress.M;
import com.suhui.task.pojo.progress.P;
import com.suhui.task.pojo.progress.P_M;
import com.suhui.task.service.Get_header;
import com.suhui.task.service.HttpRequest;
import com.suhui.task.service.My_util;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    private String URL = "http://172.16.249.145:5000/shproject_task";
//    private String URL = "http://192.168.136.131:3000";


    @Resource
    private HttpRequest httpRequest;

    @Resource
    private Get_header get_header;

    @Resource
    private My_util my_util;

    /**
     * 成员管理页面
     * 分页查询
     * 获取成员数据
     */
    @GetMapping("/get_member")
    public Result<?> member_data(String url,int limit,int offset,String order) {
        if ("".equals(url)){
            return Result.error("500","请求格式错误");
        }
        if (0 >= limit) {
            // 一页默认数据为 10 条
            limit = 10;
        }
        if ("".equals(order)) {
            // 默认按id 分页
            order = "id";
        }
        // 分页逻辑
        if (offset == 1) {
            offset = offset - 1;
        }else {
            offset = (offset-1)*limit;
        }
        Map<String,Object> param = new HashMap<>();
        param.put("limit",limit);
        param.put("offset",offset);
        param.put("order",order);
        url = this.URL + url;
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        String data_s = httpRequest.sendGet(url,param,header);
        // 将获取的数据 字符串 转换为 json格式的集合
        JSONArray data_array = JSON.parseArray(data_s);
        return Result.success(data_array);
    }

    /**
     * 成员管理页面
     * 普通表格查询
     * 获取总成员数量
     */
    @GetMapping("/get_member_num")
    public Result<?> member_data_total(String url) {
        if ("".equals(url)){
            return Result.error("500","请求格式错误");
        }
        url = this.URL + url;
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        String data_s = httpRequest.sendGet(url,null,header);
        JSONArray data_array = JSON.parseArray(data_s);
        int total = data_array.size();
        return Result.success(total);
    }

    /**
     * 成员管理页面
     * 模糊查询
     * 按指定内容搜索数据
     */
    @GetMapping("/search")
    public Result<?> member_search(String url,String name,String group) {
        if ("".equals(url)){
            return Result.error("500","请求格式错误");
        }
        if (name==null && group==null) {
            return Result.error("500","未指定姓名或组别");
        }
        url = this.URL + url;
        Map<String,Object> param = new HashMap<>();
        if (name!=null && group==null) {
            String like_name = "like.*" + name + "*";
            param.put("name",like_name);
        }
        if (name==null && group!=null) {
            String like_group = "like.*" + group + "*";
            param.put("group",like_group);
        }
        if (name!=null && group!=null) {
            String like_group = "like.*" + group + "*";
            String like_name = "like.*" + name + "*";
            param.put("group",like_group);
            param.put("name",like_name);
        }
        // 拿到有token的请求头
        Map<String,String> header = get_header.set_header();
        String data_string = httpRequest.sendGet(url,param,header);
        // 将获取的数据 字符串 转换为 json格式的集合
        JSONArray data_array = JSON.parseArray(data_string);
        return Result.success(data_array);
    }

    /**
     * 成员管理页面
     * 插入数据
     * 添加成员数据
     */
    @PostMapping("/add")
    public Result<?> member_add(@RequestBody M member) {
        if (member == null) {
            return Result.error("500","无效成员数据");
        }
        if (member.getId().isEmpty()) {
            return Result.error("500","成员学号不能为空");
        }
        member.setAsk_for_leave_all(0);
        // url
        String url = this.URL + "/member";
        // 请求token
        Map<String, String> map = get_header.set_header();
        // 数据
        String json = JSON.toJSONString(member);
        String res = httpRequest.sendPost_json_(url, json, map);
        JSONObject object = JSONObject.parseObject(res);
        if (object == null) {
            return Result.success(res);
        }
        if (object.containsKey("code")) {
            if ("23505".equals(object.get("code"))) {
                return Result.error("500","成员学号已存在");
            }
        }
        return Result.error("500","系统繁忙");
    }

    /**
     * 成员管理页面
     * 更新数据
     * 依据成员id更新成员数据
     */
    @PatchMapping("/update")
    public Result<?> member_update(@RequestBody M member) {
        if (member == null) {
            return Result.error("500","无效成员数据");
        }
        // url
        String url = this.URL + "/member?id=eq."+member.getId();
        // 请求token
        Map<String, String> map = get_header.set_header();
        // 数据
        HashMap<String, Object> map_data = new HashMap<>();
        if (member.getId() != null) {
            map_data.put("id",member.getId());
        }
        if (member.getName()!=null) {
            map_data.put("name",member.getName());
        }
        if (member.getGroup()!=null) {
            map_data.put("group",member.getGroup());
        }
        if (member.getGroup_detail()!=null) {
            map_data.put("group_detail",member.getGroup_detail());
        }
        // int类型判断为空--借助于integer类
        Integer integer = Integer.valueOf(member.getAsk_for_leave_all());
        if (integer != null) {
            map_data.put("ask_for_leave_all",member.getAsk_for_leave_all());
        }
        String data_string = httpRequest.sendPatch(url, map_data, map);
        return Result.success(data_string);
    }

    /**
     * 成员管理页面
     * 删除数据
     * 依据成员id删除成员数据
     * 同时获取成员进度id，删除进度数据
     */
    @DeleteMapping("/delete/{id}")
    public Result<?> member_delete(@PathVariable String id) {
        if (id == null) {
            return Result.error("500","无效成员id");
        }
        // 请求token
        Map<String, String> map = get_header.set_header();
        // 获取成员详细进度的 进度id  （首要：获取进度表中的数据id）
        String url1 = this.URL+ "/member_progress?select=progress_id&member_id=eq."+id;
        String p_id_string = httpRequest.sendGet(url1,null,map);
        JSONArray p_id_jsonArray = JSONArray.parseArray(p_id_string);
        // url： 删除中间表数据 ( 含外键，首要删除，会影响另外两个表的数据删除 )
        String url3 = this.URL + "/member_progress?member_id=eq."+id;
        httpRequest.sendDelete(url3,map);
        // url： 删除成员数据
        String url = this.URL + "/member?id=eq."+id;
        httpRequest.sendDelete(url,map);
        // 依次 删除进度表中相关的数据
        P_M p_m = new P_M();
        for (Object object : p_id_jsonArray) {
            p_m = JSONObject.parseObject(object.toString(), P_M.class);
            // url： 删除进度表中数据
            String url2 = this.URL+ "/progress?id=eq."+p_m.getProgress_id();
            String data_delete_p = httpRequest.sendDelete(url2,map);
        }
        return Result.success();
    }


}
